var express = require('express');
var router = express.Router();
var formidable = require('formidable')
var path = require('path')
var fs = require('fs')
var changeDAL = require('../DAL/changeDAL')
var app = require('../app')
const passport = require('passport');

/* GET home page. */
router.get('/', function(req, res, next) {
    res.send('index');
});

//上传头像
// router.post('/upload', /* passport.authenticate("jwt",{session:false}), */function(req, res, next) {
//     // var userInfo = req.body
//     console.log("11",localStorage.getItem("user_id"));
//     var form = new formidable.IncomingForm();
//     form.uploadDir = path.join(__dirname, '../', 'public',"images");
//     form.parse(req, function(err, fields, files) {
//         let filename = Object.values(files)[0].path;
//         let newName 
//         if (filename.indexOf('\\') > 0) {
//             newName = filename.substring(filename.lastIndexOf('\\') + 1, filename.length)
//         } else {
//             newName = filename
//         }
//         changeDAL.change(newName,fields,function(err) {
//             if (err) {
//                 res.json('头像上传失败')
//             } else {
//                 res.json('头像上传成功')
//             }
//         })
//     });
// });
//上传头像
router.post('/upload', passport.authenticate('jwt', { session: false }), function (req, res, next) {
    console.log('当前调用本接口的用户是：', req.user)
    var user = req.user
    var user_img = ''
    var form = new formidable.IncomingForm();
    form.uploadDir = path.join(__dirname, '..', 'public', 'images')
    form.parse(req, function (err, fields, files) {
      // console.log('fields',fields);
      console.log('files', files);
      // var url = files.myHeadImg.path
      // var url = files.file.File.path
      // console.log('url',url)
      // console.log(url.substr(url.lastIndexOf("/") + 1))
      user_img = files.myHeadImg.path.slice(files.myHeadImg.path.lastIndexOf('\\') + 1)
      changeDAL.change(user, user_img, function (err, results) {
        if (err) {
          res.json({ code: 500, msg: 'upload error' })
        } else {
          res.json({ code: 200, msg: 'upload success', data: results, src: 'http://localhost:3000/upload/' + user_img })
        }
      })
    });
  
  });
module.exports = router;